from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from datetime import datetime
import hashlib
import uuid

from ..schemas.cef import CEFRequest, CEFResponse
from ..core.tcp_client import send_xml_request
from ..core.xml_builder import build_request_xml, parse_response_xml
from ..core.utils import format_error_msg, ERROR_CODES
from ..config import settings
from ..core.logger import log_transaction
from ..core.database import get_db
from ..models.transaction import Transaction

router = APIRouter()

@router.post("/cef", response_model=CEFResponse)
async def refund_transaction(request: CEFRequest, db: Session = Depends(get_db)):
    """
    CEF 退货交易
    
    Args:
        request: CEF 交易请求
    
    Returns:
        CEF 交易响应
    """
    try:
        # 准备请求数据（自动补充必要字段）
        request_data = request.prepare_data()
        
        # 生成系统内部orderid（不同于pay_order）
        now = datetime.now()
        request_data["orderid"] = f"02{now.strftime('%Y%m%d%H%M%S')}243"  # 02 + 时间戳 + 243(随机后缀)
        
        # 记录请求日志
        log_transaction(
            trans_type="CEF",
            direction="REQUEST",
            message="Processing refund request",
            orderid=request_data.get("orderid", ""),
            pan=request.pan,
            org_trans_sn=request.org_trans_sn,
            org_rrn=request.org_rrn
        )
        
        # 构建 XML 请求报文（带 MD5 签名）
        request_xml = build_request_xml(request_data, need_md5=True)
        
        # 发送请求并接收响应
        response_xml = await send_xml_request(request_xml)
        
        # 解析响应（验证 MD5 签名）
        response_data = parse_response_xml(response_xml, verify_md5=True)
        
        # 添加错误信息
        response_data["error_msg"] = format_error_msg(
            response_data.get("resp_code", "9999"),
            ERROR_CODES
        )
        
        response = CEFResponse(**response_data)
        
        # 保存交易记录到数据库
        transaction = Transaction(
            id=str(uuid.uuid4()),
            trans_code="CEF",
            pan=request.pan,
            trans_amt=request.trans_amt,
            trans_date=response.bank_date,
            trans_time=datetime.now().strftime("%H%M%S"),
            trans_sn=response.trans_sn,
            rrn=response.rrn,
            orderid=response.orderid,
            resp_code=response.resp_code,
            bank_date=response.bank_date,
            merno=request.merno,
            terminal=request.terminal,
            org_trans_sn=request.org_trans_sn,
            org_rrn=request.org_rrn,
            pay_order=request.pay_order  # 保存外部订单号
        )
        db.add(transaction)
        db.commit()
        
        # 记录成功响应日志
        log_transaction(
            trans_type="CEF",
            direction="RESPONSE",
            message=f"Refund completed: {response.trans_sn}",
            orderid=response.orderid,
            pan=request.pan,
            resp_code=response.resp_code,
            error_msg=response.error_msg
        )
        
        return response
        
    except Exception as e:
        # 记录错误并返回统一的错误响应
        error_msg = str(e)
        error_response = CEFResponse(
            resp_code="9999",
            trans_sn="",
            bank_date=request_data.get("trans_date", ""),
            rrn="",
            orderid=request_data.get("orderid", ""),
            pan=request.pan,
            error_msg=error_msg
        )
        
        # 记录错误日志
        log_transaction(
            trans_type="CEF",
            direction="ERROR",
            message=error_msg,
            orderid=request_data.get("orderid", ""),
            pan=request.pan
        )
            
        return error_response 